import {
  omit
} from 'lodash'
import Vue from 'vue'

export const getProps = (source) => {
  if (Object.prototype.toString.call(source) === '[object Object]') {
    let components = {}
    let props = {}
    for (let key in source) {
      const value = source[key]

      if (Object.prototype.toString.call(value) === '[object Object]') {
        components[key] = omit(value, ['type', 'default'])
        if (String(value.default)) {
          props[key] = value.default
        }

        continue
      }

      if (Array.isArray(value)) {
        components[key] = {
          col: {
            span: 24
          }
        }
        continue
      }

      components[key] = {
        col: {
          span: 24
        }
      }
    }
    return [components, props]
  }

  return []
}

export const getSize = ({ width, height, minWidth, minHeight, maxWidth, maxHeight }) => {
  minWidth = minWidth === void 0 ? 0 : Math.max(0, minWidth)
  minHeight = minHeight === void 0 ? 0 : Math.max(0, minHeight)
  maxWidth = maxWidth === 'none' ? width : Math.max(minWidth, maxWidth)
  maxHeight = maxHeight === 'none' ? height : Math.max(minHeight, maxHeight)

  const ratio = height / width

  if (width < minWidth) {
    width = minWidth
    height = minWidth * ratio
  }
  if (height < minHeight) {
    width = minHeight / ratio
    height = minHeight
  }
  if (width > maxWidth) {
    width = maxWidth
    height = maxWidth * ratio
  }
  if (height > maxHeight) {
    width = maxHeight / ratio
    height = maxHeight
  }
  const length = Math.pow(10, 5)
  width = Math.round((width * length)) / length
  height = Math.round((height * length)) / length

  return {
    width: width,
    height: height,
    residueW: maxWidth - width,
    residueH: maxHeight - height
  }
}

export const getScale = ({ width, height, minWidth, minHeight, maxWidth, maxHeight }) => {
  minWidth = minWidth === void 0 ? 0 : Math.max(0, minWidth)
  minHeight = minHeight === void 0 ? 0 : Math.max(0, minHeight)
  maxWidth = maxWidth === 'none' ? width : Math.max(minWidth, maxWidth)
  maxHeight = maxHeight === 'none' ? height : Math.max(minHeight, maxHeight)

  let scale = maxWidth / maxHeight < width / height ? maxWidth / width : maxHeight / height
  return scale
}

export const setData = (source, data = {}) => {
  if (Object.prototype.toString.call(source) === '[object Object]') {
    for (let key in data) {
      Vue.set(source, key, data[key])
    }
  }
}
